package com.demo.config.tus;

import lombok.extern.slf4j.Slf4j;
import me.desair.tus.server.TusFileUploadService;
import me.desair.tus.server.exception.TusException;
import me.desair.tus.server.upload.UploadInfo;
import org.noear.solon.Solon;
import org.noear.solon.core.Props;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

@Slf4j
public class TusFileUploadResolver {

    private final TusFileUploadService tusFileUploadService;

    private final Props tusProperties;

    public TusFileUploadResolver(TusFileUploadService tusFileUploadService, Props tusProperties) {
        this.tusFileUploadService = tusFileUploadService;
        this.tusProperties = Solon.cfg().getProp("tus");
    }

    public void upload(HttpServletRequest request, HttpServletResponse response,String fileId) {
        try {
            tusFileUploadService.process(request, response);
            final String uploadURI = request.getRequestURL().toString();
            final UploadInfo uploadInfo = tusFileUploadService.getUploadInfo(uploadURI);
            if (uploadInfo != null && !uploadInfo.isUploadInProgress()) {
                final InputStream uploadedBytes = tusFileUploadService.getUploadedBytes(uploadURI);
                final String appUploadDirectory = tusProperties.get("finalFilePath");
                new File(appUploadDirectory).mkdirs();
                final Path outPut = Paths.get(appUploadDirectory).resolve(uploadInfo.getFileName());
                Files.copy(uploadedBytes, outPut, StandardCopyOption.REPLACE_EXISTING);
                tusFileUploadService.deleteUpload(uploadURI);
                uploadedBytes.close();
            }
        } catch (TusException | IOException e) {
            log.error("",e);
            throw new RuntimeException("上传失败，原因：" + e.getMessage(), e);
        }}
}
